package com.jyx.picval;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class getImg extends HttpServlet{
	
	private static final int WIDTH = 78;//验证码宽度
	private static final int HEIGHT = 23;//验证码高度
	//ctrl+shift+o
	//重写HTTPServlet的service方法
	public void service(HttpServletRequest req,HttpServletResponse resp)
		throws IOException{
		//创建图像数据的缓冲区
		//BufferedIamge.TYPE_INT_RGB表示具有八位RGB颜色的分量图像
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
		Graphics gs = image.getGraphics();//获取画图工具
		gs.setColor(new Color(255));//设置颜色
		gs.fillRect(0, 0, WIDTH, HEIGHT);//绘制画布尺寸 填充颜色 
		
		StringBuilder s = new StringBuilder();//定义一个可变的String 类型的变量 s 保存生成的内容
		Random r = new Random();//实例化随机数的对象
		for (int i = 0; i < 5; i++) {
			int num = r.nextInt(10);//随机生成0到9之间的整数
			char c = (char)(r.nextInt(26)+65);//随机生成A—Z之间的字母
			String[] str = new String[2]  ;//生成一个二维数组保存上面的随机数
			str[0] = String.valueOf(num);//将num转化成String的类型
			str[1] = String.valueOf(c);//将c转换为String并存放到str数组中	
			s.append(str[r.nextInt(2)]);//字符串追加
		}
		System.out.println(s);
		//设置验证码字体的颜色：淡黄色
		gs.setColor(new Color(255,255,100));
		//设置字体风格：字体
		gs.setFont(new Font(null,Font.ITALIC,20));
		//将生成的内容放到图片上
		gs.drawString(s.toString(),5,20);//绘制制定的字符串到image图片上
		
		for (int i = 0; i < 6; i++) {//随机生成干扰线
			gs.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
			gs.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT),r.nextInt(WIDTH), r.nextInt(HEIGHT));
		}
		resp.setContentType("image/jpeg");//表示输出的是一张图片的格式，图片格式是jpeg
		OutputStream out = resp.getOutputStream();//获取输出流
		ImageIO.write(image,"jpeg",out);//把图片输出
	}
}
